package org.lex.ftp.ui.bookmark;

import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.lex.ftp.util.bookmark.Bookmark;
import org.lex.ftp.util.bookmark.Site;


public class BookmarkTree extends JTree {
	public BookmarkTree(Bookmark bookmark) {
		super(new BookmarkTreeNode(bookmark));
		this.setCellRenderer(new BookmarkNodeRenderer());
	}

	public Bookmark getRootBookmark() {
		return ((BookmarkTreeNode) this.getModel().getRoot()).getFolder();
	}

	public BookmarkTreeNode getSelectBookmarkNode() {
		TreePath path = getSelectionPath();
		if (null == path)
			return null;
		return (BookmarkTreeNode) path.getLastPathComponent();
	}

	public void addSite(Site site) {
		this.addNode(new BookmarkTreeNode(site));
	}

	public void addGroup(Bookmark folder) {
		this.addNode(new BookmarkTreeNode(folder));
	}

	public void deleteSelected() {
		BookmarkTreeNode node = this.getSelectBookmarkNode();
		if (null == node || null == node.getParent())
			return;
		StringBuilder buf = new StringBuilder();
		buf.append("<html>Are you sure to delete ");
		if (null != node.getSite())
			buf.append("site");
		else
			buf.append("group");
		buf.append(" \"").append(node.getName()).append("\"?");
		buf.append("<br>You can't undo this operation!</html>");
		int opt = JOptionPane.showConfirmDialog(SwingUtilities.getWindowAncestor(this), buf.toString(), "Delete", JOptionPane.YES_NO_CANCEL_OPTION,
				JOptionPane.QUESTION_MESSAGE);
		if (JOptionPane.YES_OPTION == opt) {
			BookmarkTreeNode parent = (BookmarkTreeNode) node.getParent();
			node.removeFromParent();
			parent.getFolder().remove(node.getFolder());
			parent.getFolder().remove(node.getSite());
			this.getModel().nodeStructureChanged(parent);
		}
	}

	private void addNode(BookmarkTreeNode node) {
		BookmarkTreeNode parent = this.findNearestFolder(this.getSelectBookmarkNode());
		System.out.println("Add [" + node.getName() + "] to [" + parent.getName() + "]");
		parent.add(node);
		if (null != node.getFolder())
			parent.getFolder().add(node.getFolder());
		if (null != node.getSite())
			parent.getFolder().add(node.getSite());
		this.getModel().nodeStructureChanged(parent);
		this.setSelectionPath(new TreePath(node.getPath()));
	}

	private BookmarkTreeNode findNearestFolder(BookmarkTreeNode node) {
		while (null != node && null == node.getFolder())
			node = (BookmarkTreeNode) node.getParent();
		if (null == node)
			node = (BookmarkTreeNode) this.getModel().getRoot();
		return node;
	}

	public DefaultTreeModel getModel() {
		return (DefaultTreeModel) super.getModel();
	}
}
